// API base URL
const API_BASE_URL = "";

// DOM elements
const videoForm = document.getElementById('videoForm');
const uploadForm = document.getElementById('uploadForm');
const projectsList = document.getElementById('projectsList');
const videosList = document.getElementById('videosList');
const uploadProjectId = document.getElementById('uploadProjectId');
const loading = document.getElementById('loading');

// Show loading indicator
function showLoading() {
    loading.classList.remove('hidden');
}

// Hide loading indicator
function hideLoading() {
    loading.classList.add('hidden');
}

// Format date for display
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

// Generate video from text
videoForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const prompt = document.getElementById('prompt').value;
    const projectTitle = document.getElementById('projectTitle').value;
    
    if (!prompt.trim()) {
        alert('请输入视频描述');
        return;
    }
    
    showLoading();
    
    try {
        // Create project if title is provided
        let projectId = null;
        if (projectTitle.trim()) {
            const projectResponse = await fetch(`${API_BASE_URL}/projects/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title: projectTitle,
                    description: `项目用于生成关于"${prompt.substring(0, 50)}"的视频`
                })
            });
            
            if (projectResponse.ok) {
                const projectData = await projectResponse.json();
                projectId = projectData.id;
            }
        }
        
        // Generate video
        const response = await fetch(`${API_BASE_URL}/generate-video-from-text/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                prompt: prompt,
                project_id: projectId
            })
        });
        
        if (response.ok) {
            const data = await response.json();
            alert(`视频生成任务已启动！\n视频ID: ${data.video_id}\n状态: ${data.status}`);
            
            // Refresh videos list
            await loadVideos();
        } else {
            const errorData = await response.json();
            alert(`生成视频失败: ${errorData.detail || '未知错误'}`);
        }
    } catch (error) {
        console.error('Error generating video:', error);
        alert(`生成视频时发生错误: ${error.message}`);
    } finally {
        hideLoading();
    }
});

// Upload video
uploadForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const videoFile = document.getElementById('videoFile').files[0];
    const selectedProjectId = uploadProjectId.value;
    
    if (!videoFile) {
        alert('请选择视频文件');
        return;
    }
    
    showLoading();
    
    try {
        const formData = new FormData();
        formData.append('file', videoFile);
        if (selectedProjectId) {
            formData.append('project_id', selectedProjectId);
        }
        
        const response = await fetch(`${API_BASE_URL}/upload-video/`, {
            method: 'POST',
            body: formData
        });
        
        if (response.ok) {
            const data = await response.json();
            alert(`视频上传成功！\n视频ID: ${data.video_id}\n文件名: ${data.filename}`);
            
            // Refresh videos list
            await loadVideos();
        } else {
            const errorData = await response.json();
            alert(`上传视频失败: ${errorData.detail || '未知错误'}`);
        }
    } catch (error) {
        console.error('Error uploading video:', error);
        alert(`上传视频时发生错误: ${error.message}`);
    } finally {
        hideLoading();
    }
});

// Load projects
async function loadProjects() {
    try {
        const response = await fetch(`${API_BASE_URL}/projects/`);
        if (response.ok) {
            const projects = await response.json();
            
            if (projects.length > 0) {
                projectsList.innerHTML = '';
                
                projects.forEach(project => {
                    const projectElement = document.createElement('div');
                    projectElement.className = 'project-item';
                    projectElement.innerHTML = `
                        <h3>${project.title}</h3>
                        <p>ID: ${project.id}</p>
                        <p>创建时间: ${formatDate(project.created_at)}</p>
                        <p>${project.description || '无描述'}</p>
                    `;
                    projectsList.appendChild(projectElement);
                });
                
                // Update project dropdown for upload form
                uploadProjectId.innerHTML = '<option value="">无项目</option>';
                projects.forEach(project => {
                    const option = document.createElement('option');
                    option.value = project.id;
                    option.textContent = project.title;
                    uploadProjectId.appendChild(option);
                });
            } else {
                projectsList.innerHTML = '<p>暂无项目</p>';
                uploadProjectId.innerHTML = '<option value="">无项目</option>';
            }
        }
    } catch (error) {
        console.error('Error loading projects:', error);
        projectsList.innerHTML = '<p>加载项目失败</p>';
    }
}

// Load videos
async function loadVideos() {
    try {
        const response = await fetch(`${API_BASE_URL}/videos/`);
        if (response.ok) {
            const videos = await response.json();
            
            if (videos.length > 0) {
                videosList.innerHTML = '';
                
                videos.forEach(video => {
                    const videoElement = document.createElement('div');
                    videoElement.className = 'video-item';
                    
                    // Format file size
                    const fileSizeMB = (video.size / (1024 * 1024)).toFixed(2);
                    
                    videoElement.innerHTML = `
                        <h3>${video.filename}</h3>
                        <p>ID: ${video.id}</p>
                        <p>大小: ${fileSizeMB} MB</p>
                        <p>创建时间: ${formatDate(video.created_at)}</p>
                        ${video.project_id ? `<p>项目ID: ${video.project_id}</p>` : ''}
                        <p>路径: ${video.file_path}</p>
                    `;
                    videosList.appendChild(videoElement);
                });
            } else {
                videosList.innerHTML = '<p>暂无视频</p>';
            }
        } else {
            videosList.innerHTML = '<p>加载视频失败</p>';
        }
    } catch (error) {
        console.error('Error loading videos:', error);
        videosList.innerHTML = '<p>加载视频失败</p>';
    }
}

// Initialize the app
async function initApp() {
    showLoading();
    
    try {
        // Test API connection
        const healthResponse = await fetch(`${API_BASE_URL}/health`);
        if (!healthResponse.ok) {
            alert('无法连接到API服务器，请确保后端服务正在运行');
        }
        
        // Load initial data
        await loadProjects();
        await loadVideos();
    } catch (error) {
        console.error('Error initializing app:', error);
        alert('初始化应用时发生错误');
    } finally {
        hideLoading();
    }
}

// Start the app when the page loads
document.addEventListener('DOMContentLoaded', initApp);
